package com.example.shiro;

import com.example.common.SessionCons;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.UnknownSessionException;
import org.apache.shiro.session.mgt.eis.AbstractSessionDAO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.io.Serializable;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * @Author: 胡成
 * @Version: 0.0.1V
 * @Date: 2019/3/21
 * @Description: 类描述
 **/
@Slf4j
public class RedisSessionDao extends AbstractSessionDAO {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    protected Serializable doCreate(Session session) {
        Serializable sessionId = SessionCons.TOKEN_PREFIX + UUID.randomUUID().toString().replaceAll("-", "");
        assignSessionId(session, sessionId);
        redisTemplate.opsForValue().set(sessionId, session);
        redisTemplate.expire(String.valueOf(sessionId), 30, TimeUnit.SECONDS);
        log.info("create shiro session ,sessionId is :{}", sessionId.toString());
        return sessionId;
    }

    @Override
    protected Session doReadSession(Serializable sessionId) {
        log.info("获取session:{}", sessionId);
        Session session = (Session) redisTemplate.opsForValue().get(sessionId);
        return session;
    }

    @Override
    public void update(Session session) throws UnknownSessionException {
        log.info("修改session:{}", session.getId());
        if (null != session && null != session.getId()) {
            redisTemplate.opsForValue().set(session.getId(), session);
        }
    }

    @Override
    public void delete(Session session) {
        log.info("delete shiro session ,sessionId is :{}", session
                .getId().toString());
        redisTemplate.opsForValue().getOperations().delete(session.getId());
    }

    @Override
    public Collection<Session> getActiveSessions() {
        Set<Serializable> keys = redisTemplate.keys(SessionCons.TOKEN_PREFIX_KEY);
        if (keys.size() == 0) {
            return Collections.emptySet();
        }
        List<Session> sessionList = redisTemplate.opsForValue().multiGet(keys);
        return Collections.unmodifiableCollection(sessionList);
    }
}
